<template>
  <div class="el-card__body basic-container">
    <div class="">

    <el-form ref="form" :model="form" label-width="80px">
      <el-form-item label="标题">
        <el-input v-model="form.Title"></el-input>
      </el-form-item>
      <el-form-item label="分类">
        <el-select v-model="form.CategoryID" placeholder="请选择分类">
          <el-option v-for="(item,index) in categoryData" :key="index"  :value="item.id" :label="item.Name"></el-option>
        </el-select>
      </el-form-item>

      <el-form-item label="tag">
        <el-select v-model="form.TagID" placeholder="请选择tag">
          <el-option v-for="(item,index) in tagData" :key="index"  :value="item.id" :label="item.Name"></el-option>
        </el-select>
      </el-form-item>

      <el-form-item label="作者">
        <el-select v-model="form.UserID" placeholder="请选择作者">
          <el-option v-for="(item,index) in userData" :key="index"  :value="item.id" :label="item.Username"></el-option>
        </el-select>
      </el-form-item>

      <el-form-item label="描述">
        <el-input v-model="form.Desc"></el-input>
      </el-form-item>

      <el-form-item label="封面图片">
        <el-upload
          :headers="headers"
          class="avatar-uploader"
          action="/admin/sys-file/upload"
          :show-file-list="false"
          :on-success="handleAvatarSuccess"
          :before-upload="beforeAvatarUpload">
          <img v-if="imageUrl" :src="imageUrl" class="avatar">
          <i v-else class="el-icon-plus avatar-uploader-icon"></i>
        </el-upload>
      </el-form-item>
    </el-form>
    </div>
    <div class="markdown-body editormd-preview-container" ref="catalog" id="custom-toc-container">#custom-toc-container</div>
    
    <div id="test-editor">
    <textarea style="display:none;">
      ### 关于 Editor.md
      **Editor.md** 是一款开源的、可嵌入的 Markdown 在线编辑器（组件），基于 CodeMirror、jQuery 和 Marked 构建。
    </textarea>
    </div>
    <el-button type="primary" @click="save">提交</el-button>

  </div>
</template>
<script>
import store from '@/store'

import {
  addObj
} from '@/api/cms/article'

import {
  fetchCategoryList,
} from '@/api/cms/category'

import {
  fetchUserList,
} from '@/api/cms/author'

import {
  fetchTagList,
} from '@/api/cms/tag'

  export default {
    data: function () {
      return {
        headers: {
        'Authorization': 'Bearer ' + store.getters.access_token,
      },
        doc: {},
        editor: null,
        form: {
          Title: '',
          CategoryID: '',
          TagID: '',
          MdContent: '',
          Content: '',
          PreContent: '',
          UserID: '',
          Desc: '',
          CoverImageUrl: '',
          Catalog: ''
        },
        imageUrl: '',
        categoryData: [],
        tagData: [],
        userData: [],
        page: {
          total: 0, // 总页数
          currentPage: 1, // 当前页数
          pageSize: 20 // 每页显示多少条
        }
      }
    },
    created: function () {
      this.getCategoryList(this.page)
      this.getTagList(this.page)
      this.getUserData(this.page)
    },
    methods: {
      getCategoryList(page, params) {
        this.tableLoading = true
        fetchCategoryList(Object.assign({
          current: page.currentPage,
          size: page.pageSize
        }, params, this.searchForm)).then(response => {
          this.categoryData = response.data.data.lists
          this.tableLoading = false
        }).catch(() => {
          this.tableLoading = false
        })
      },
      getTagList(page, params) {
        this.tableLoading = true
        fetchTagList(Object.assign({
          current: page.currentPage,
          size: page.pageSize
        }, params, this.searchForm)).then(response => {
          this.tagData = response.data.data.lists
          console.log(this.tagData)
          this.tableLoading = false
        }).catch(() => {
          this.tableLoading = false
        })
      },
      getUserData(page, params){
        fetchUserList(Object.assign({
          current: page.currentPage,
          size: page.pageSize
        }, params, this.searchForm)).then(response => {
          this.userData = response.data.data.lists
          console.log(this.tagData)
          this.tableLoading = false
        }).catch(() => {
          this.tableLoading = false
        })
      },
      save(){
        this.form.update_by = '博羸'
        addObj(this.form).then(data => {
          this.$message({
            showClose: true,
            message: '添加成功',
            type: 'success'
          })
          this.reset()
        }).catch(() => {

        })
      },

      handleAvatarSuccess(res, file) {
        this.imageUrl = URL.createObjectURL(file.raw);
        this.form.CoverImageUrl = res.data.url
      },
      beforeAvatarUpload(file) {
        const isLt2M = file.size / 1024 / 1024 < 2;

        if (!isLt2M) {
          this.$message.error('上传头像图片大小不能超过 2MB!');
        }
        return isLt2M;
      },
      reset(){
        this.form = {
          Title: '',
          CategoryID: '',
          TagID: '',
          MdContent: '',
          Content: '',
          PreContent: '',
          UserID: '',
          Desc: ''
        }
      }
    },
    mounted: function () {
      var that = this
      var editor = editormd("test-editor", {
            // width  : "100%",
            // height : "100%",
            path   : "cdn/editor.md/lib/",
            //theme: "dark",//工具栏主题
            //previewTheme: "dark",//预览主题
            //editorTheme: "pastel-on-dark",//编辑主题
            saveHTMLToTextarea: true, // 保存 HTML 到 Textarea
            htmlDecode: "style,script,iframe",
            emoji: false,
            codeFold : true, // 代码折叠
            taskList: true,
            tocm: true,         // Using [TOCM]
            tex: true,                   // 开启科学公式TeX语言支持，默认关闭
            flowChart: true,             // 开启流程图支持，默认关闭
            sequenceDiagram: true,       // 开启时序/序列图支持，默认关闭,
            syncScrolling: "single",
            width  : "90%",
            height : 720,
            autoHeight : true,
            onpreviewing : function() {
                console.log("onpreviewing =>", this, this.id, this.settings);
            },
            onpreviewed : function() {
                console.log("onpreviewed =>", this, this.id, this.settings);
            },
            onchange : function() {
              that.form.MdContent = editor.getMarkdown()    // 获取 Markdown 源码
              that.form.Content = editor.getPreviewedHTML()
              that.form.PreContent = editor.getPreviewedHTML()
              that.form.Catalog = that.$refs.catalog.innerHTML
            }
        });

        editor.config({
            tocContainer: "#custom-toc-container",
            tocDropdown: false
        })

        that.form.MdContent = editor.getMarkdown()       // 获取 Markdown 源码
        that.form.Content = editor.getPreviewedHTML()  
    }
  }
</script>
<style scoped>
@import '/cdn/editor.md/css/editormd.min.css';
@import '/cdn/editor.md/css/editormd.preview.min.css';
.CodeMirror-wrap{
  min-height: 300px;
}
#test-editor{
  /*margin-bottom: 200px;*/
}
.CodeMirror-scroll {
  min-height: 400px;
}
.CodeMirror-wrap{
  min-height: 500px !important;
}
.editormd-preview{
  min-height: 400px !important;
}
.el-card__body{
  margin-left: 10px;
  background-color: white;
  padding-top: 10px;
  padding-right: 30px;
}
.avatar-uploader .el-upload {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
  }
  .avatar-uploader .el-upload:hover {
    border-color: #409EFF;
  }
  .avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 178px;
    height: 178px;
    line-height: 178px;
    text-align: center;
  }
  .avatar {
    width: 178px;
    height: 178px;
    display: block;
  }
  .CodeMirror-code{
    margin-top: 50px!important;
  }
</style>